/** 资产盘点计划 */

import React, {useEffect, useState} from 'react'
import {Button, Space, message} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {connect} from 'umi'
import {ArrowUpOutlined, ArrowDownOutlined} from '@ant-design/icons'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
import {
	getStockatekDataListPage,
	getStocktakeDataList,
	inventoryPlanImport,
	stocktakeDataList,
} from '@/service/storage/assetInventoryPlan'
import {inputField, dictData} from './data'
import {downloadDocumentUrl} from '@/service/common/download'
import BatchUpload from '@/components/BatchUpload'
import {modalApi} from '@/utils/modalReq'
import {modelSeriesFun, translateDataToTree} from '@/utils/common'
import {getAllCitys, getCompany, getHolderDictInfo} from '@/service/common'
import {getCarTypeList} from '@/service/carMessage/list'

interface CityOption {
	value: string | number
	label: string
	children?: CityOption[]
}

const formItemLayout = {
	labelCol: {flex: '120px'},
	wrapperCol: {flex: '1'},
}

const archives = (props: any) => {
	const {query} = props.location
	const [dataSource, setDataSource] = useState<any[]>([])
	const [columns, setColumns] = useState<ColumnsType<any>>([])
	const [loading, setLoading] = useState(false)
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)
	const [searchData, setSearchData] = useState<any[]>([])
	const [total, setTotal] = useState()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [formItems, setFormItems] = useState<any>([])
	const [citysList, setCitysList] = useState<CityOption[]>([]) // 初始化城市
	const [carTypeList, setCarTypeList] = useState<any>([]) // 初始化品牌车系车系
	const [companyData, setCompanyData] = useState<any[]>([]) // 初始化所属公司
	const stocktakeType = window.location.href.split('stocktakeType=')[1]
	const [filterData, setFilterData] = useState<any>()
	const [formValues, setFormValues] = useState<any>({})
	const [holderDict, setHolderDict] = useState([]) // 初始化持有方

	useEffect(() => {
		/** 初始化-持有方数据 */
		getHolderDictInfo({type: 'holder'}).then((res: any) => {
			if (res?.success) {
				setHolderDict(res?.data)
			}
		})
		/** 初始化城市 */
		getAllCitys().then((res: any) => {
			if (res?.success) {
				setCitysList(() => res.data)
			}
		})
		/** 获取品牌车系 */
		getCarTypeList().then((res: any) => {
			if (res?.success) {
				setCarTypeList(modelSeriesFun(res.data))
			}
		})
		/** 获取所属公司数据 */
		getCompany({merchantId: props?.user?.orgId}).then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res.data)
				setCompanyData(list as any)
			}
		})
	}, [])
	// 获取盘点清单查询条件列表
	useEffect(() => {
		getStocktakeDataList({planId: query?.planId})
			.then((res: any) => {
				if (res?.success) {
					setFilterData(res?.data)
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}, [])
	useEffect(() => {
		if (filterData) {
			const newFormItems: any[] = []
			// const { selectFieldList, customFieldList } = filterData || {}
			// const newArr = selectFieldList.concat(customFieldList)
			const newFormValues: any = {}
			filterData?.selectFieldList?.forEach((item: any, index: number) => {
				if (item?.value) {
					newFormValues[item.name] = Number(item?.value)
				}
				const str = `group${Math.ceil((index + 1) / 3)}`
				// 判断该项为输入框还是选择框
				const isInput =
					(item?.nameZh && inputField?.includes(item?.nameZh)) ||
					item?.type === 1
				const formData: any = {
					type: isInput ? 'input' : 'select',
					label: item?.nameZh || item?.name,
					name: item?.name,
					key: item?.name,
					disabled: !!item?.value,
				}
				if (!isInput) {
					// 持有方
					if (item.name === 'holder_id') {
						formData.keys = 'value'
						formData.title = 'valueName'
						formData.items = holderDict
					} else if (item.name === 'org_id') {
						formData.type = 'treeSelect'
						formData.keys = 'id'
						formData.title = 'name'
						formData.treeData = companyData
					} else if (item.name === 'city_id') {
						formData.type = 'cascader'
						formData.fieldNames = {
							label: 'name',
							value: 'id',
							children: 'cityInfoList',
						}
						formData.items = citysList
					} else if (item.name === 'fashion_id') {
						formData.keys = 'id'
						formData.title = 'fullName'
						formData.items = carTypeList
					} else {
						formData.keys = 'key'
						formData.title = 'label'
						formData.items = dictData[item.name]
					}
				}
				const datas: any = newFormItems?.find(
					(items) => items?.key === str,
				)
				if (datas) {
					datas.groupItems.push(formData)
				} else {
					newFormItems?.push({
						type: 'group',
						key: str,
						groupItems: [formData],
					})
				}
			})
			const latsData = newFormItems[newFormItems.length - 1].groupItems
			if (latsData?.length === 1) {
				latsData.splice(latsData?.length, 0, {}, {})
			} else if (latsData?.length === 2) {
				latsData.splice(latsData?.length, 0, {})
			}
			setFormValues(newFormValues)
			setFormItems(newFormItems)
		}
	}, [filterData, holderDict, citysList, carTypeList, companyData])

	// 获取盘点清单列表
	const getData = () => {
		setLoading(true)
		stocktakeDataList({
			...params,
			planId: query?.planId,
			selectFieldList: searchData,
		})
			.then((res: any) => {
				if (res?.success) {
					const arr: any = []
					const {header, contents} = res.data
					const newColumns: any[] = header.map((value: any) => ({
						title: value,
						dataIndex: value,
						align: 'center',
						width: 150,
					}))
					setColumns(newColumns)
					contents?.forEach((item: any[]) => {
						const newData: any = {}
						item?.forEach((items, index) => {
							newData[header[index]] = items
						})
						arr.push(newData)
					})
					setDataSource(arr)
					setLoading(false)
					setTotal(res?.data?.total)
				} else {
					setLoading(false)
				}
			})
			.catch((err) => {
				setDataSource([])
				message.error(err)
				setLoading(false)
			})
	}
	useEffect(() => {
		getData()
	}, [params])

	const onFinish = (values: any) => {
		const newValues = Object.keys(values)?.map((item) => {
			if (item === 'city_id') {
				return {name: item, value: values?.[item]?.[1]}
			}
			return {name: item, value: values?.[item]}
		})
		setSearchData(newValues)
		setParams({
			current: 1,
			size: 10,
		})
	}

	const onReset = () => {
		const newValues = Object.keys(formValues)?.map((item) => ({
			name: item,
			value: formValues?.[item],
		}))
		setSearchData(newValues)
		setParams({
			current: 1,
			size: 10,
		})
	}

	const errorColumns: any = [
		{
			title: '车辆ID',
			dataIndex: '车辆ID',
			align: 'center',
			width: 200,
		},
		{
			title: '失败原因',
			dataIndex: 'errorMsg',
			align: 'center',
			width: 200,
		},
	]

	return (
		<div className={styles.inventoryList}>
			<div className={styles.content}>
				{formItems && formItems?.length ? (
					<div className={styles.search}>
						<SearchForm
							onFinish={onFinish}
							onReset={onReset}
							values={formValues}
							formItems={formItems}
							formLayout={formItemLayout}
						/>
					</div>
				) : (
					''
				)}

				<div className={styles.btnlist}>
					<Space size={12}>
						<Button
							icon={<ArrowDownOutlined />}
							className={styles.import}
							ghost
							size="small"
							onClick={() => {
								downloadDocumentUrl({
									resourceId: '193',
									queryDesc: '盘点清单导出,resourceId:193',
									queryParam: {
										planId: query?.planId,
										selectFieldList: searchData,
									},
								})
							}}>
							导出
						</Button>
						{stocktakeType === '2' ? (
							<Button
								icon={<ArrowUpOutlined />}
								className={styles.warning}
								ghost
								size="small"
								onClick={() => setIsUploadModalOpen(true)}>
								导入抽盘结论
							</Button>
						) : (
							''
						)}
					</Space>
				</div>
				<CustomTable
					params={params}
					columns={columns}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataSource}
				/>
			</div>
			<BatchUpload
				typeUp={false}
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				importData={inventoryPlanImport}
				onTableList={getStockatekDataListPage}
				getListData={getData}
				planId={query?.planId}
				uploadFileUrl={`${modalApi.carMessage}/stocktake-data-list/import/check`}
				columns={errorColumns}
			/>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(archives)
